const express = require('express')
const {
  User,
  addSchema,
  editUserValidate
} = require('../model/userdb');
const router = express.Router()
const bcrypt = require('bcryptjs'); //导入加密模块 
router.get('/', async function (req, res) {
  res.render('admin/login', {})
}) //网站根目录下跳转到登陆页面
router.get('/login', async function (req, res) {
  res.render('admin/login', {})
}) //设置登陆页面路由
router.post('/login', async function (req, res) {
  const {
    email,
    password
  } = req.body;
  if (email.trim().length == 0 || password.trim().length == 0) {
    return res.status(400).send('<h4>邮件地址或者密码错误</h4>');
  }
  console.log(email, password);

  let user = await User.findOne({
    email
  });
  // console.log('当前登陆：' + user.username);

  if (user) {

    let isValid = await bcrypt.compare(password, user.password); //比对密码
    if (isValid) { // 比对成功
      req.session.username = user.username;
      req.app.locals.userInfo = user;
      // console.log(req.app.locals.userInfo);
      if ('normal' == user.role) {
        return res.redirect('/home')
      }
      console.log('当前登陆：' + user.username);
      res.redirect('/admin/user/list')
    } else {
      // 没有查询到用户
      res.status(400).send('<h4>邮件地址或者密码错误</h4>')
    }
  } else {
    console.log(2);
    // 没有查询到该用户不执行操作
    res.status(400).send('<h4>邮件地址或者密码错误</h4>')
  }
}) //获取登陆页面请求并进行登陆判断
router.get('/logout', (req, res) => {
  req.session.destroy(() => { //删除服务器端的session
    res.clearCookie('connect.sid') //删除cookie
    res.redirect('/admin/login'); //重定向到登录页
    req.app.locals.userInfo = null; //清空用户信息
  })
}) //设置退出登陆模块
router.get('/user/list', async (req, res) => {
  let page = req.query.page || 1; // 接收客户端传递过来的当前页参数
  let pagesize = 5; //每页显示的条数
  let usersize = await User.countDocuments(); //获取数据库中的总数据
  let total = Math.ceil(usersize / pagesize) //总页数 但是结果要向上取整
  let start = (page - 1) * pagesize; //当前页从第几条数据查起
  let user = await User.find().limit(pagesize).skip(start);
  res.render('admin/user', {
    users: user,
    page: page,
    total: total
  })
}) //设置用户列表页
router.get('/user/add', (req, res) => {
  res.render('admin/user-add')
}) //设置用户添加路由
router.post('/user/add', async function (req, res) {
  // 定义对象的验证规则
  // 实施验证
  const result = await addSchema(req.body).catch(err => err)
  if (result instanceof Error) {

    let message = result.message;
    res.render('admin/user-add', {
      message
    })
    return result.message;
  }

  let userpd = await User.findOne({
    email: req.body.email
  });
  // console.log(userpd);
  if (userpd) {
    let message = '当前邮箱被占用'
    res.render('admin/user-add', {
      message
    })
  }
  let pwd = req.body.password; //获取到输入的密码
  let salt = await bcrypt.genSalt(10); //生成随机字符串
  let pass = await bcrypt.hash(pwd, salt)
  req.body.password = pass;
  await User.create(req.body);
  // 将页面重定向到用户列表页面
  res.redirect('/admin/user/list')

}) //获取用户添加的信息做验证
router.get('/user/edit/:id', async (req, res) => {
  const {
    id
  } = req.params
  let message;
  let user = await User.findOne({
    _id: id
  }).catch(err => null)
  if (!user) {
    message = '找不到该用户'
    user = {}
  }
  res.render('admin/user-edit', {
    user,
    message
  })
}) //设置修改页面路由
router.post('/user/edit', async (req, res) => {
  const {
    id,
    pwd,
    ...reqData
  } = req.body
  // 实施验证
  let result = await editUserValidate(req.body).catch(err => err)
  const user = await User.findOne({
    _id: id
  }).catch(err => null)
  // console.log(result );
  if (result instanceof Error) {
    let message = result.message;
    res.render('admin/user-edit', {
      user,
      message
    })
    return result.message;
  }
  let isValid = await bcrypt.compare(reqData.password , user.password);
  if (isValid){
    res.render('admin/user-edit', {
      user,
      message:'修改的密码不能和近期的一样'
    })
    return result.message;
  }
  let pwdd = req.body.password; //获取到输入的密码
  let saltt = await bcrypt.genSalt(10); //生成随机字符串
  let passs = await bcrypt.hash(pwdd, saltt)
  reqData.password = passs;


  result = await User.updateOne({
    _id: id
  }, reqData)

  if (!result.ok) {
    let message = '服务器异常，请稍后重试'
    res.render('admin/user-edit', {
      user,
      message
    })
  }

  res.redirect('/admin/user/list')
}) //用户修改存进数据库
router.get('/user/delete', async (req, res) => {
  const {
    id
  } = req.query

  const user = await User.findOneAndDelete({
    _id: id
  }).catch(err => null)
  res.redirect('/admin/user/list')
}) //用户删除操作
module.exports = router;